package com.banshuibao.bsb_android;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.banshuibao.bsb_android.push.UmPushHandler;
import com.banshuibao.bsb_android.push.UmPushNotificationClickHandler;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.LogUtil;
import com.bugtags.library.Bugtags;
import com.bugtags.library.BugtagsOptions;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
import com.mob.MobSDK;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.tag.TagManager;

import java.util.ArrayList;

/**
 * Created by wangpan on 2017/3/16.
 */

public class MyApplication extends MultiDexApplication {

    public static MyApplication applicationInstance;

    public GetLoginInfo loginInfo;

    private String cookieId;

    private PushAgent pushAgent;

    private SharedPreferences sharedPreferences;

    //添加activity的集合
    ArrayList<Activity> aal = new ArrayList<Activity>();

    private SharedPreferences.Editor edit;

    public ArrayList<Activity> getAal() {
        return aal;
    }

    public void setAal(ArrayList<Activity> aal) {
        this.aal = aal;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationInstance = this;
        BugtagsOptions options = new BugtagsOptions.Builder().
                trackingLocation(false).//是否获取位置，默认 true
                trackingCrashLog(false).//是否收集crash，默认 true
                trackingConsoleLog(true).//是否收集console log，默认 true
                trackingUserSteps(true).//是否收集用户操作步骤，默认 true
                trackingNetworkURLFilter("(.*)").//自定义网络请求跟踪的 url 规则，默认 null
                build();
        //在这里初始化
        if (Constants.DEBUG.isDebug()) {
            Bugtags.start(BuildConfig.DEBUG ? "d90254c7e16a2871b75c0e443986ea90" : "d8e3223c1b9d467a6989fac779697b89", this, Bugtags.BTGInvocationEventBubble, options);
        }
        loginInfo = GetLoginInfo.getLoginInfoInstance(this);
        initSp();
        initPush();
        initFileDownloader();
        //友盟统计非测试环境下统计
        MobclickAgent.setDebugMode(Constants.DEBUG.isDebug());
        //mob分享
        MobSDK.init(this);
        /**
         * 设置推送alias tag
         * 根据身份判断快速咨询跳转哪个页面
         * 0 事务所用户 1解税宝用户 2 事务所管理员 3 咨询师 4 专家
         */

        if (loginInfo != null) {
            String userId = loginInfo.readUser().getUserId();
            String role = loginInfo.readUser().getRole();
            String type = "";
            if (!TextUtils.isEmpty(loginInfo.readUser().getCookieId())) {
                if (role.equals("2") || role.equals("3") || role.equals("4")) {
                    type = "tax";
                } else {
                    type = "user";
                }
                setAlias(userId);
                addTag("1", type);
            }
        }
    }

    private void initFileDownloader() {
        FileDownloader.setupOnApplicationOnCreate(this)
                .connectionCreator(new FileDownloadUrlConnection
                        .Creator(new FileDownloadUrlConnection.Configuration()
                        .connectTimeout(15000) // set connection timeout.
                        .readTimeout(15000) // set read timeout.
                ))
                .commit();
    }

    public GetLoginInfo getLoginInfo() {
        return loginInfo.readUser();
    }

    public String getCookieId() {
        if (TextUtils.isEmpty(cookieId)) {
            cookieId = getLoginInfo().getCookieId();
        }
        return cookieId;
    }

    public SharedPreferences getMainSharedPreferences() {
        return sharedPreferences;
    }

    public void restCookieId() {
        this.cookieId = "";
    }

    //友盟推送初始化
    private void initPush() {
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE,
                "132cd1b47628d7372cb827c5a319c23c");
        pushAgent = PushAgent.getInstance(this);
        pushAgent.DEBUG = Constants.DEBUG.isDebug();
        pushAgent.setMessageHandler(new UmPushHandler());
        pushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        pushAgent.setNotificationClickHandler(new UmPushNotificationClickHandler());
        pushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String s) {
             //   LogUtil.e("TAG", "成功token+++:" + s);
            }

            @Override
            public void onFailure(String s, String s1) {
             //   LogUtil.e("TAG", "失败token---:" + s1);
            }
        });
    }

    public void saveAlias(String alias) {
        getMainSharedPreferences().edit().putString("alias", alias).apply();
    }

    public String getMainAlias() {
        return getMainSharedPreferences().getString("alias", "");
    }

    public void setAlias(final String alias) {
        pushAgent.addAlias(alias, "alias", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                LogUtil.e(s);
                if (b)
                    saveAlias(alias);
            }
        });
    }

    public void removeAlias(String alias) {
        pushAgent.deleteAlias(alias, "alias", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                LogUtil.e(s.toString());
            }
        });
    }

    /**
     * 推送添加标签
     */
    public void addTag(String... tags) {
        pushAgent.getTagManager().addTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(final boolean isSuccess, final ITagManager.Result result) {
            }
        }, tags);
    }

    /**
     * 推送删除标签
     */
    public void deleteTag(String... tags) {
        pushAgent.getTagManager().deleteTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(final boolean isSuccess, final ITagManager.Result result) {
            }
        }, tags);
    }

    //添加activity方法
    public void addActivity(Activity activity) {
        aal.add(activity);
    }

    //移除
    public void removeActivity(Activity activity) {
        aal.remove(activity);
    }

    //销毁
    public void finishActivity() {
        //遍历集合
        if (aal != null && aal.size() > 0)
            for (Activity activity : aal) {
                //判断是否销毁
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }

            }
    }

    //销毁
    public void finishActivity(Activity activityNow) {
        //遍历集合
        if (aal != null && aal.size() > 0)
            for (Activity activity : aal) {
                //判断是否销毁
                if (activity != null && !activity.isFinishing()) {
                    if (!activity.getClass().getName().equals(activityNow.getClass().getName())) {
                        activity.finish();
                    }
                }
            }
    }

    public SharedPreferences getLiveQuestionTimeShare() {
        return this.getSharedPreferences("live_question_time", MODE_PRIVATE);
    }

    public void initSp() {
        sharedPreferences = this.getSharedPreferences("main_sp", Context.MODE_PRIVATE);
        edit = sharedPreferences.edit();
        edit.putBoolean("isUp", false);
        edit.putBoolean("upShow", false).commit();
    }
}
